package org.xinjiang.data.migration.flush.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xinjiang.data.migration.common.response.Param;
import org.xinjiang.data.migration.flush.convert.LocAreaFlushConvert;
import org.xinjiang.data.migration.flush.dto.res.FlushResultDTO;
import org.xinjiang.data.migration.flush.service.ILocAreaFlushService;
import org.xinjiang.data.migration.hainan.convert.FlushLogConvert;
import org.xinjiang.data.migration.hainan.entity.HnLocAreaEntity;
import org.xinjiang.data.migration.hainan.service.IFlushLogService;
import org.xinjiang.data.migration.hainan.service.IHnLocAreaService;
import org.xinjiang.data.migration.xinjiang.entity.SysAreaFenceEntity;
import org.xinjiang.data.migration.xinjiang.service.SysAreaFenceService;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class LocAreaFlushServiceImpl implements ILocAreaFlushService {
    @Resource
    private IHnLocAreaService locAreaService;

    @Resource
    private SysAreaFenceService sysAreaFenceService;

    @Resource
    private LocAreaFlushConvert locAreaFlushConvert;

    @Autowired
    private IFlushLogService flushLogService;

    @Autowired
    private FlushLogConvert flushLogConvert;

    @Override
    public FlushResultDTO flushAll() {
        FlushResultDTO result = new FlushResultDTO();
        long pageSize = 100L; // 每页大小1000
        long currentPage = 1L; // 当前页码

        while (true) {
            Param pageable = new Param();
            pageable.setPageSize(pageSize);
            pageable.setPageNum(currentPage);
            IPage<HnLocAreaEntity> pageList = locAreaService.pageList(pageable);

            if (pageList.getRecords().isEmpty()) {
                // 没有更多数据，退出循环
                break;
            }

            // 处理当前页的数据
            List<SysAreaFenceEntity> insertList = pageList.getRecords().stream().map(locAreaFlushConvert::convert).collect(Collectors.toList());

            processPageData(insertList, result);

            // 获取下一页数据
            currentPage++;
        }

        return result;
    }

    public void processPageData(List<SysAreaFenceEntity> insertList, FlushResultDTO flush) {
        if (CollectionUtils.isEmpty(insertList)) {
            return;
        }

        for (SysAreaFenceEntity entity : insertList) {
            try {
                sysAreaFenceService.save(entity);
                flush.setSuccessCount(flush.getSuccessCount() + 1);
            } catch (Exception e) {
                log.error("e===========", e);
                flush.setErrCount(flush.getErrCount() + 1);
                flushLogService.save(flushLogConvert.convertLocArea(entity, e.getMessage()));
            }
        }
    }
}
